package com.eslserver.action.login;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.core.ESLAuthAware;
import com.eslserver.core.ESLServerPageDispatcher;
import com.eslserver.to.User;

@SuppressWarnings("serial")
public class UserLogin extends HttpServlet implements ESLAuthAware,
		ESLServerPageDispatcher {
	public static final Logger LOG = LoggerFactory.getLogger(UserLogin.class);

	private final String LOGIN_ERROR = "Login failed. Please verify your username / password or contact the System Administrator";

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");

		RequestDispatcher dispatcher = req.getRequestDispatcher(LOGIN_PAGE);

		if (username != null) {
			// TODO: hardcode user object for now, need to change to User
			// and UserDAO objects
			User user = User.createUser();
			user.setPassword("sipix");

			if (user != null && user.getPassword() != null
					&& user.getPassword().equals(password)) {
				HttpSession session = req.getSession();
				session.setAttribute(ATTRIBUTE_USER, user);

				dispatcher = req.getRequestDispatcher(MAIN_DASHBOARD);
			} else {
				req.setAttribute("error", LOGIN_ERROR);
			}
		}
		dispatcher.forward(req, resp);
	}
}
